package BIO;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author:谢君臣
 * @Date:2021/7/23-15:56
 * @version:1.0
 * @function:
 */
public class FileClient1 {
    private String filePath;
    private static int port;
    private static InetAddress inetAddress;

    static {
        port = 9999;
        try {
            inetAddress = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public String upload() throws IOException {
        Socket socket = new Socket(inetAddress, port);
        // 创建文件
        File file = new File(filePath);
        // 获取输入流
        FileInputStream inputStream = new FileInputStream(file);
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        // 写数据
        dos.writeUTF("." + file.getName().split(".")[1]);
        int length = 0;
        byte[] buffer = new byte[1024];
        while ((length = inputStream.read(buffer)) != -1) {
            dos.write(buffer, 0, length);
            dos.flush();
        }
        socket.shutdownOutput();
        // 获取放回结果
        byte[] buffer_return = new byte[1024];
        InputStream inputStream1 = socket.getInputStream();
        inputStream1.read(buffer_return);
        // 关闭输入出流
        inputStream1.close();
        dos.close();
        inputStream.close();
        socket.close();
        return new String(buffer_return);
    }
}
